#include "mdichild.h"
#include<QFile>
#include<QTextStream>
#include<QMessageBox>
#include<QFileInfo>
#include<QApplication>
#include<QFileDialog>
#include<QCloseEvent>
#include<QPushButton>
#include<QMenu>
MdiChild::MdiChild(QWidget *parent) : QTextEdit(parent)
{
    setAttribute(Qt::WA_DeleteOnClose);
    isUntitled=true;
}

void MdiChild::newFile()
{
    static int num=1;
    isUntitled=true;
    curFile=tr("UnTitled%1.txt").arg(num++);
    setWindowTitle(curFile+"[*]"+tr(" - Sate"));
    connect(document(),SIGNAL(contentsChange(int,int,int)),this,SLOT(documentWasModified()));
}

void MdiChild::documentWasModified()
{
    setWindowModified(document()->isModified());
}


bool MdiChild::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly|QFile::Text))
    {
        QMessageBox::warning(this,tr("Sate"),tr("error, can't open file"));
        return false;
    }
    QTextStream in(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();
    setCurrentFile(fileName);
    connect(document(),SIGNAL(contentsChanged()),this,SLOT(documentWasModified()));
    return true;
}

void MdiChild::setCurrentFile(const QString &filename)
{
    curFile=QFileInfo(filename).canonicalFilePath();
    isUntitled=false;
    setWindowModified(false);
    document()->setModified(false);
    setWindowTitle(userFriendlyCurrentFile()+"[*]");
}

QString MdiChild::userFriendlyCurrentFile()
{
    return QFileInfo(curFile).fileName();
}

bool MdiChild::save()
{
    if(isUntitled)    //file haven't been saved yet
        return saveAs();
    else                    //file have been saved
        return saveFile(curFile);
}

bool MdiChild::saveAs()
{
    QString fileName=QFileDialog::getSaveFileName(this);
    if(fileName.isEmpty())
        return false;
    return saveFile(fileName);
}

bool MdiChild::saveFile(const QString &fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly|QFile::Text))
    {
        QMessageBox::warning(this,tr("Sate"),tr("error, can't open file"));
        return false;
    }
    QTextStream out (&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    out<<toPlainText();
    QApplication::restoreOverrideCursor();
    setCurrentFile(fileName);
    return true;
}



void MdiChild::closeEvent(QCloseEvent *event)
{
    if (maybeSave()) { // 如果maybeSave()函数返回true，则关闭窗口
        event->accept();
    } else {   // 否则忽略该事件
        event->ignore();
    }
}


bool MdiChild::maybeSave()  // 是否需要保存
{
    if (document()->isModified()) { // 如果文档被更改过
        QMessageBox box;
        box.setWindowTitle(tr("多文档编辑器"));
        box.setText(tr("是否保存对“%1”的更改？")
                    .arg(userFriendlyCurrentFile()));
        box.setIcon(QMessageBox::Warning);

        // 添加按钮，QMessageBox::YesRole可以表明这个按钮的行为
        QPushButton *yesBtn = box.addButton(tr("是(&Y)"),QMessageBox::YesRole);

        box.addButton(tr("否(&N)"),QMessageBox::NoRole);
        QPushButton *cancelBtn = box.addButton(tr("取消"),
                                               QMessageBox::RejectRole);
        box.exec(); // 弹出对话框，让用户选择是否保存修改，或者取消关闭操作
        if (box.clickedButton() == yesBtn)// 如果用户选择是，则返回保存操作的结果
            return save();
        else if (box.clickedButton() == cancelBtn) // 如果选择取消，则返回false
            return false;
    }
    return true; // 如果文档没有更改过，则直接返回true
}



void MdiChild::contextMenuEvent(QContextMenuEvent *e) // 右键菜单事件
{
    QMenu *menu = new QMenu; // 创建菜单，并向其中添加动作
    QAction *undo = menu->addAction(tr("撤销(&U)"),this,
                                    SLOT(undo()),QKeySequence::Undo);
    undo->setEnabled(document()->isUndoAvailable());
    QAction *redo = menu->addAction(tr("恢复(&R)"),this,
                                    SLOT(redo()),QKeySequence::Redo);
    redo->setEnabled(document()->isRedoAvailable());
    menu->addSeparator();
    QAction *cut = menu->addAction(tr("剪切(&T)"),this,
                                   SLOT(cut()),QKeySequence::Cut);
    cut->setEnabled(textCursor().hasSelection());
    QAction *copy = menu->addAction(tr("复制(&C)"),this,
                                    SLOT(copy()),QKeySequence::Copy);
    copy->setEnabled(textCursor().hasSelection());
    menu->addAction(tr("粘贴(&P)"),this,SLOT(paste()),QKeySequence::Paste);
    QAction *clear = menu->addAction(tr("清空"),this,SLOT(clear()));
    clear->setEnabled(!document()->isEmpty());
    menu->addSeparator();
    QAction *select = menu->addAction(tr("全选"),this,
                                      SLOT(selectAll()),QKeySequence::SelectAll);
    select->setEnabled(!document()->isEmpty());
    menu->exec(e->globalPos()); // 获取鼠标的位置，然后在这个位置显示菜单
    delete menu; // 最后销毁这个菜单
}
